package wzh.hc.view;

import java.io.*;
import java.net.URI;
import java.net.URL;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.List;
import java.util.ResourceBundle;

import static wzh.hc.view.DPIFormatter.*;

import wzh.hc.model.HashComputer;
import javafx.application.*;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

public class MainStage extends Application implements Initializable {
	URI file;
	HashComputer hashComputer=new HashComputer();
	
	List<String> hashTypeList = Arrays.asList("MD2", "MD5", "SHA-1", "SHA-224",
			"SHA-256", "SHA-384", "SHA-512");
	int hashTypeDefaultValueIndex = 1;
	String rightStyle = "-fx-text-fill:green";
	String wrongStyle = "-fx-text-fill:red";
	@FXML
	ComboBox<String> hashTypeCBox;
	@FXML
	TextField filePathTField;
	@FXML
	TextField expectedValueTField;
	@FXML
	TextField actualValueTField;

	Stage stage;

	public static void main(String[] args) {
		Application.launch(MainStage.class);
	}

	@Override
	public void start(Stage stage) throws Exception {
		this.stage = stage;
		
		final double width=16;
		stage.setWidth(cmToPx(width));
		stage.setHeight(cmToPx(width*0.618));
		
		Parent root = FXMLLoader.load(getClass().getResource("MainStage.fxml"));
		Scene scene = new Scene(root, 600, 400);
		stage.setScene(scene);
		stage.setTitle("Hash Computer");
		stage.show();
	}
	
	@Override
	public void initialize(URL url, ResourceBundle resource) {
		hashTypeCBox.getItems().addAll(hashTypeList);
		hashTypeCBox.setValue(hashTypeList.get(hashTypeDefaultValueIndex));
	}

	FileChooser fileChooser;

	FileChooser getFileChooser() {
		if (fileChooser == null) {
			fileChooser = new FileChooser();
		}
		return fileChooser;
	}

	@FXML
	void onSelectFile(ActionEvent e) {
		File file = getFileChooser().showOpenDialog(stage);
		if (file != null) {
			filePathTField.setText(file.getAbsolutePath());
			this.file = file.toURI();
		}
	}

	@FXML
	void onCompute(ActionEvent e) {
		String result;
		try {
			result = hashComputer.compute(file,hashTypeCBox.getValue());
		} catch (NoSuchAlgorithmException exception) {
			result=exception.getMessage();
		}
		String ev = expectedValueTField.getText();
		actualValueTField.setText(result);
		if (result.equals(ev)) {
			actualValueTField.setStyle(rightStyle);
		} else {
			actualValueTField.setStyle(wrongStyle);
		}
	}
	
}
